/**
 * Created by dale on 2017/10/9.
 */
$(document).ready(function () {
    var form = new xhForm($('#xh_form'));
    form.parse();

    var stateType = addressUri.getParam('stateType');
    if(carInfo==1) {
        $('#bt_form_save').show();
        parseTime();
    }else {
        if(stateType == 1){
            parseTime();
        }
    }

    var  flag;
    // $("#sDriverName").combotree({
    //     url:baseUrl+'lm/car/getDepStaff',
    //     required:false,
    //     cascadeCheck:false,
    //     panelHeight:150,
    //     onBeforeSelect: function (node) {
    //         flag = false;
    //         if(node.id.split('-')[0]=='D'){
    //             flag = true;
    //             var t = $('#sDriverName').combotree('tree');
    //             t.tree('toggle',node.target);
    //             return false;
    //         }
    //     },
    //     onHidePanel:function () {
    //         if(flag){
    //             $('#sDriverName').combotree('setValue','');
    //             $('#sDriverName').combotree('showPanel');
    //         }
    //         return false;
    //     },
    //     onLoadSuccess:function () {
    //         if(carInfo != 1){
    //             $('#sDriverName').combotree('setValue',carInfo['sDriverName']);
    //         }
    //     }
    // });
    $('#sDriverName').select2({
        placeholder: '选择司机',
        data: drivers,
        allowClear: false
    });

    $('#sTravellers').select2({
        placeholder: '选择出行人员',
        data: leavers,
        allowClear: true,
        multiple:true
    });

    $('[name=iCUId]').select2();
    if(carInfo.sProvince!=null){
        var provinceName=carInfo.sProvince;
        var cityName=carInfo.sCity;
        var countryName=carInfo.sCountry;
        $.ajax({
            url  :baseUrl+'customer/customer/getAreaBynames',
            type : 'POST',
            data : {'qnames':[provinceName,cityName,countryName]},
            dataType : 'JSON',
            success:function (data) {
                BindSelect('provinceSelect',baseUrl+"customer/customer/getAreaData?pid=0",data[0]);
                BindSelect('citySelect',baseUrl+"customer/customer/getAreaData?pid="+data[0]['id'],data[1]);
                BindSelect('countrySelect',baseUrl+"customer/customer/getAreaData?pid=0"+data[1]['id'],data[2]);
            }
        });
    }else {

        BindSelect('provinceSelect',baseUrl+"customer/customer/getAreaData?pid=0",null);
        BindSelect('citySelect',baseUrl+"customer/customer/getAreaData?pid=1",null);
        BindSelect('countrySelect',baseUrl+"customer/customer/getAreaData?pid=1",null);
    }

    $('[name=iCUId]').on("change", function (e) {
        var iCUId =  $('[name=iCUId]').val();
        $.ajax({
            url  :baseUrl+'customer/customer/getCusInfo',
            type : 'POST',
            data : {iCUId:iCUId},
            dataType : 'JSON',
            success:function (data) {
                if(data['area'] != null){
                    BindSelect('provinceSelect',baseUrl+"customer/customer/getAreaData?pid=0",data['area'][0]);
                    BindSelect('citySelect',baseUrl+"customer/customer/getAreaData?pid="+data['area'][0]['id'],data['area'][1]);
                    BindSelect('countrySelect',baseUrl+"customer/customer/getAreaData?pid=0"+data['area'][1]['id'],data['area'][2]);
                }
                $('[name=mDestination]').val(data['sDetailedAddress']).trigger('change');
            }
        });
    });

    $("#provinceSelect").on("change", function (e) {
        var pid = $("#provinceSelect").val();
        $("#citySelect").val("").trigger('change');
        $("#countrySelect").val("").trigger('change');
        if(pid!=''){
            BindSelect("citySelect", baseUrl+"customer/customer/getAreaData?pid="+pid);
        }
    });

    $("#citySelect").on("change", function (e) {
        var pid = $("#citySelect").val();
        $("#countrySelect").val("").trigger('change');
        if(pid!=''){
            BindSelect("countrySelect", baseUrl+"customer/customer/getAreaData?pid="+pid);
        }
    });


    if(carInfo != 1){
        if(stateType == 2){
            $('#bt_form_add').text('审批');
            $('#bt_form_desc').show();
            $('.xh-area-form table tr:last').before('<tr> <td><label>审批意见</label></td> <td colspan="3"><textarea name="mDepText" type="text" rows="2" class="form-control" must="true"></textarea></td> </tr>');
        }else  if(stateType == 3){
            $('#bt_form_desc').show();
            $('#bt_form_fixData').show();
        }
        form.fill(carInfo);
        if(carInfo['iCUId']!=null){
            $('[name=iCUId]').val(carInfo['iCUId']).trigger('change');
        }
        if(carInfo['sTravellers']!=null){
            $('#sTravellers').val(carInfo['sTravellers'].split(',')).trigger('change');
        }
        if(carInfo['sDriverName']){
            $('#sDriverName').val(carInfo['sDriverName']).trigger('change');
        }
    }

    form.bindRequired($('#bt_form_add,#bt_form_save')).triggerRequired();

    //查看审批信息
    $('#bt_form_desc').click(function () {
        var id = $("[name=iUCId]").val();
        window.top.xhTop.showModal({
            title:'查看审批意见',
            content:'<iframe src="'+baseUrl+'lm/car/descList/'+id+'" style="height: 350px;border-style: none;padding: 0px;width: 100%;"></iframe>',
            size:'lg'
        });
    });
    //返回
    $('#bt_form_back').click(function () {
        $('#listTable tr:first',parent.document).show();
        $('#listTable tr:last',parent.document).hide();
    });

    //提交
    $('#bt_form_add').click(function () {
        var $this = $(this);
        $this.addClass('disabled');
        changeStr();
        $.ajax({
            url:baseUrl+'lm/car/saveUseCar',
            data:$('#xh_form').serialize(),
            type:'POST',
            success:function (data) {
                window.parent.useCarList.dataGridReload();
                $('#bt_form_back').click();
            },
            error:function (data) {
                $this.removeClass("disabled");
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });
    //保存
    $('#bt_form_save').click(function () {
        var $this = $(this);
        $this.addClass('disabled');
        $('[name=iState]').val(0);
        changeStr();
        $.ajax({
            url:baseUrl+'lm/car/saveUseCar',
            data:$('#xh_form').serialize(),
            type:'POST',
            success:function (data) {
                window.parent.useCarList.dataGridReload();
                $('#bt_form_back').click();
            },
            error:function (data) {
                $this.removeClass("disabled");
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });

    $('#bt_form_fixData').click(function () {
        changeStr();
        $.ajax({
            url:baseUrl+'lm/car/saveFixData',
            data:$('#xh_form').serialize(),
            type:'POST',
            success:function (data) {
                window.parent.useCarList.dataGridReload();
                $('#bt_form_back').click();
            },
            error:function (data) {
                $this.removeClass('disabled');
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });

    
    // modalBind.bindClick();

});


function changeStr() {
    if($('#provinceSelect').select2('data')[0]==undefined){
        // alert('请选择省');
        window.top.swal({
            title:'省未选择',
            text:'请你选择省',
            timer:700,
            showConfirmButton:false,

        });

        return false;
    }else if($('#citySelect').select2('data')[0]==undefined){
        // alert('请选择市');
        window.top.swal({
            title:'市未选择',
            text:'请选择市',
            timer:700,
            showConfirmButton:false,
        });
        return false;
    }else if($('#countrySelect').select2('data')[0]==undefined){
        // alert('请选择区');
        window.top.swal({
            title:'区未选择',
            text:'请选择区',
            timer:700,
            showConfirmButton:false,

        });
        return false;
    }
    $('[name=sProvince]').val($('#provinceSelect ').select2('data')[0].text);
    $('[name=sCity]').val($('#citySelect ').select2('data')[0].text);
    $('[name=sCountry]').val($('#countrySelect ').select2('data')[0].text);
}


function parseTime() {
    $("[name=tStartTime]").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        language: 'zh-CN',
        minView: "hour",
        autoclose: true
    });
    $("[name=tEndTime]").datetimepicker({
        format: 'yyyy-mm-dd hh:ii',
        language: 'zh-CN',
        minView: "hour",
        autoclose: true
    }).on('changeDate', function (ev) {
        var startTime = $("[name=tStartTime]").val();
        var endTime = $("[name=tEndTime]").val();
        if (!startTime || !endTime) {
            window.top.swal(
                '',
                '开始时间结束时间不能为空',
                'error'
            );
            return false;
        }
        $.ajax({
            url: baseUrl + 'lm/car/carEnum',
            type: 'POST',
            data: {startTime: startTime, endTime: endTime},
            dataType: 'json',
            success: function (data) {
                var dom = $('[name=iCarId]');
                dom.empty();
                var str = '<option value="" style="display: none" selected>请选择</option>';
                $.each(data, function (id, text) {
                    str += '<option value="' + id + '">' + text + '</option>';
                });
                dom.append(str);
            },
            error: function (data) {
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
        $.ajax({
            url: baseUrl + 'lm/car/carDriver',
            type: 'POST',
            data: {startTime: startTime, endTime: endTime},
            dataType: 'json',
            success: function (data) {
                var dom = $('[name=sDriverName]');
                dom.empty();
                var str = '<option value="" style="display: none" selected>请选择</option>';
                $.each(data, function (index, item) {
                    str += '<option value="' + item['id'] + '">' + item['text'] + '</option>';
                });
                dom.append(str);
            },
            error: function (data) {
                window.top.swal(
                    data['responseText'],
                    '',
                    'error'
                );
            }
        });
    });
}

function BindSelect(ctrlName, url,area) {
    var control = $('#' + ctrlName);
    //设置Select2的处理
    control.select2({
        placeholder:'请选择',
        templateResult:  function formatRepo(repo){
            return repo.text
        },
        templateSelection: function (repo) {
            if(repo.id!=""){
                $('#select2-'+ctrlName+'-container').parent().removeClass('warn-color').addClass('success-color');
            }
            return repo.text;
        },
        escapeMarkup: function (m) {
            $('#select2-'+ctrlName+'-container').parent().addClass('warn-color');
            return m;
        }
    });

    //绑定Ajax的内容
    $.getJSON(url, function (data) {
        control.empty();//清空下拉框
        if(area==null){
            control.append("<option value='' style='display: none;' selected>请选择</option>");
            $.each(data, function (id,item) {
                control.append("<option value='" + item['id'] + "'>" + item['text'] + "</option>");

            });
        }else {

            $.each(data, function (id,item) {
                if(area['id']==item['id']){
                    control.append("<option value='" + item['id'] + "' selected>" + item['text'] + "</option>");
                }else {
                    control.append("<option value='" + item['id'] + "'>" + item['text'] + "</option>");
                }

            });
        }
    });
}